<template>
  <div>
    <el-drawer
      :title="title"
      :before-close="handleClose"
      :visible.sync="goodFormDialogVisiable"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      size="40%"
    >
      <div class="demo-drawer__content">
        <h4>商品-基础信息</h4>
        <el-form
          :model="commodityForm"
          :rules="commodityFormRule"
          ref="commodityFormRef"
        >
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="commodityName"
          >
            <el-input
              v-model="commodityForm.commodityName"
              autocomplete="off"
              :disabled="action === 'detail'"
              maxlength="11"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="商品编号" :label-width="formLabelWidth">
            <el-input disabled placeholder="商品编号，系统自动生成"></el-input>
          </el-form-item>
          <el-form-item
            label="所属分类"
            :label-width="formLabelWidth"
            prop="categoryId"
          >
            <treeselect
              v-model="commodityForm.categoryId"
              :options="categoryOptions"
              :normalizer="normalizer"
              :show-count="true"
              placeholder="请选择"
              :disabled="action === 'detail'"
            />
          </el-form-item>
          <el-form-item
            label="零售价格"
            :label-width="formLabelWidth"
            prop="retailPrice"
          >
            <el-input
              v-model="commodityForm.retailPrice"
              autocomplete="off"
              :disabled="action === 'detail'"
              maxlength="11"
            ></el-input>
            元
          </el-form-item>
          <el-form-item
            label="销售价格"
            :label-width="formLabelWidth"
            prop="salePrice"
          >
            <el-input
              v-model="commodityForm.salePrice"
              autocomplete="off"
              :disabled="action === 'detail'"
              maxlength="11"
            ></el-input>
            元
          </el-form-item>
          <el-form-item
            label="库存"
            :label-width="formLabelWidth"
            prop="inventory"
          >
            <el-input
              v-model="commodityForm.inventory"
              autocomplete="off"
              :disabled="action === 'detail'"
              maxlength="11"
            ></el-input>
            个
          </el-form-item>
          <el-form-item
            label="图片"
            :label-width="formLabelWidth"
            style="position: relative"
          >
            <el-upload
              class="avatar-uploader"
              :action="imgUpConfig.addressUrl"
              :headers="imgUpConfig.headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :disabled="action === 'detail'"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件,且不超过5M
              </div>
            </el-upload>
            <div class="deleimg-icon" v-if="imageUrl">
              <i class="el-icon-delete" @click="handleRemove"></i>
            </div>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button
            v-show="action !== 'detail'"
            type="primary"
            @click="handleSubmit"
            >确 定</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import { getNonOilCategoryTreeApi } from "@/api/nonOil/class";
import { addCommodityInfoApi, editCommodityInfoApi } from "@/api/nonOil/goods";
export default {
  name: "GoodForm",
  components: { Treeselect },
  props: {
    goodFormDialogVisiable: {
      type: Boolean,
      default: false,
    },
    action: {
      type: String,
      default: "add",
    },
    currentGoodInfo: {
      type: Object,
      default: () => {},
    },
  },

  data() {
    // 分类id
    let checkCategory = (rule, value, callback) => {
      if (!this.commodityForm.categoryId) callback(new Error("请选择分类"));
      callback();
    };
    // 零售价格
    let checkRetailPrice = (rule, value, callback) => {
      let amount = Number(String(value).trim());
      const reg = /^\d+(\.\d{1,2})?$/;
      if (!value) return callback();
      if (value < 0) return callback(new Error("金额不能小于等于0"));
      if (Number.isNaN(amount)) return callback(new Error("请输入合法数字"));
      if (!reg.test(amount)) return callback(new Error("金额最多保留两位小数"));
      callback();
    };

    // 销售价格
    let checkSalePrice = (rule, value, callback) => {
      let amount = Number(String(value).trim());
      const reg = /^\d+(\.\d{1,2})?$/;
      if (value === "") return callback(new Error("请输入金额"));
      if (amount < 0) return callback(new Error("金额不能小于0"));
      if (Number.isNaN(amount)) return callback(new Error("请输入合法数字"));
      if (!reg.test(amount)) return callback(new Error("金额最多保留两位小数"));
      callback();
    };

    // 库存
    let checkInventory = (rule, value, callback) => {
      let amount = Number(String(value).trim());
      const reg = /^\d+(\.\d{0,0})?$/;
      if (!value) return callback(new Error("请输入数量"));
      if (value <= 0) return callback(new Error("数量不能小于等于0"));
      if (Number.isNaN(amount)) return callback(new Error("请输入合法数字"));
      if (!reg.test(amount)) return callback(new Error("请输入整数"));
      callback();
    };

    return {
      formLabelWidth: "80px",
      //   添加商品
      commodityForm: {
        commodityName: "", //  商品名称
        categoryId: null, // 所属分类
        retailPrice: "", // 零售价格
        salePrice: "", // 销售价格
        inventory: "", // 库存
      },
      categoryOptions: [],
      loading: false,
      imageUrl: "",
      imgUpConfig: {
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        addressUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      },
      commodityFormRule: {
        commodityName: [
          { required: true, message: "请输入商品名称", trgger: "blur" },
        ],
        categoryId: [
          { required: true, validator: checkCategory, trgger: "blur" },
        ],
        retailPrice: [
          { required: false, validator: checkRetailPrice, trigger: "blur" },
        ],
        salePrice: [
          { required: true, validator: checkSalePrice, trgger: "blur" },
        ],
        inventory: [
          { required: true, validator: checkInventory, trgger: "blur" },
        ],
      },
    };
  },
  watch: {
    // 展开抽屉的时候就调换分类树
    goodFormDialogVisiable(val) {
      if (val) {
        this.getNonOilCategoryTree();
        this.commodityForm = this.currentGoodInfo; // 数据回显
        this.imageUrl = this.currentGoodInfo.image; // 图片回显
      }
    },
  },
  computed: {
    title() {
      const type = {
        add: "新增商品",
        edit: "编辑商品",
        detail: "查看商品",
      };
      return type[this.action];
    },
  },
  methods: {
    // 删除图片
    handleRemove(file) {
      console.log(file);
      this.imageUrl = "";
      this.commodityForm.image = "";
    },
    // 关闭抽屉
    handleClose() {
      this.$emit("update:goodFormDialogVisiable", false);
      this.resetForm("commodityFormRef");
    },
    // 获取分类树
    async getNonOilCategoryTree() {
      const res = await getNonOilCategoryTreeApi();
      this.categoryOptions = this.handleTree(res.data.children, "categoryId"); // 编辑分类下拉项
    },

    /** 转换分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children,
      };
    },
    // 图片上传前的校验
    beforeAvatarUpload(file) {
      const imgtypes = ["image/jpeg", "image/png"];
      if (!imgtypes.includes(file.type)) {
        this.msgError("图片只能是jpg或png格式");
        return false;
      }
      let isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.msgError("图片大小不能超过5m");
        return false;
      }
    },
    // 图片上传成功
    handleAvatarSuccess(response, file, fileList) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.commodityForm.image = response.url;
      console.log(response, file, fileList);
    },
    // 提交
    handleSubmit() {
      this.$refs.commodityFormRef.validate((valid) => {
        if (valid) {
          if (this.currentGoodInfo.commodityId) {
            // 编辑
            const params = { ...this.commodityForm };
            editCommodityInfoApi(params).then((res) => {
              this.msgSuccess("编辑商品成功");
              this.handleClose();
              this.$emit("reloadData");
            });
          } else {
            // 新增
            addCommodityInfoApi(this.commodityForm).then((res) => {
              this.msgSuccess("添加商品成功");
              this.handleClose();
              this.$emit("reloadData");
            });
          }
        } else {
          console.log("error submit");
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .demo-drawer {
  .deleimg-icon {
    width: 178px;
    height: 178px;
    position: absolute;
    left: 0;
    top: 0;
    font-size: 20px;
    color: #fff;
    background: rgba(0, 0, 0, 0.4);
    i {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%);
    }

    :hover {
      cursor: pointer;
    }
  }

  overflow: auto;
  .el-drawer__header {
    border-bottom: 1px solid #ddd;
    padding-bottom: 20px;
    font-size: 18px;
  }

  .el-drawer__body {
    padding: 20px;

    .demo-drawer__content {
      .demo-drawer__footer {
        text-align: end;
      }
    }

    // 输入框
    .el-form-item__content {
      display: flex;
      align-items: center;
      .el-input {
        margin-right: 10px;
      }
      //   所属分类css
      .vue-treeselect__control {
        height: 40px;
        line-height: 40px;
      }
    }

    /* 图片样式 */
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>
